package org.jeecg.modules.pipe.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.constant.DeviceConstant;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.device.entity.DevDeviceInfo;
import org.jeecg.modules.device.entity.DevDeviceRecord;
import org.jeecg.modules.device.mapper.DevDeviceInfoMapper;
import org.jeecg.modules.device.mapper.DevDeviceRecordMapper;
import org.jeecg.modules.pipe.entity.MonitorPoint;
import org.jeecg.modules.pipe.mapper.MonitorPointMapper;
import org.jeecg.modules.pipe.service.IMonitorPointService;
import org.jeecg.modules.pipe.vo.PipeMarkerVo;
import org.jeecg.modules.pipe.vo.PipeQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 监测点
 * @Author: jeecg-boot
 * @Date:   2024-05-18
 * @Version: V1.0
 */
@Service
public class MonitorPointServiceImpl extends ServiceImpl<MonitorPointMapper, MonitorPoint> implements IMonitorPointService {

    @Autowired
    private MonitorPointMapper monitorPointMapper;
    @Autowired
    private DevDeviceInfoMapper devDeviceInfoMapper;
    @Autowired
    private DevDeviceRecordMapper deviceRecordMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public List<PipeMarkerVo> getMonitorPointMarker(PipeQueryVo queryVo) {
        return monitorPointMapper.getMonitorPointMarker(queryVo);
    }

    @Override
    public List<Map<String, Object>> getDeviceListReadTimeData(String pointId) {
        List<DevDeviceInfo> list = devDeviceInfoMapper.selectList(Wrappers.<DevDeviceInfo>lambdaQuery()
                .eq(DevDeviceInfo::getDelFlag,0).eq(DevDeviceInfo::getPointId,pointId));

        List<Map<String, Object>> recordVoLs=new ArrayList<>();
        for (DevDeviceInfo deviceInfo : list) {

            /**3.缓存设备数据*/
            Map<String, Object> map = (Map<String, Object>) redisUtil.hget(DeviceConstant.DEVICE_REALTIME_DATA, deviceInfo.getDeviceCode());

            if(null != map && map.size()>0){
                recordVoLs.add(map);
            }else{
                DevDeviceRecord deviceRecord = deviceRecordMapper.selectOne(Wrappers.<DevDeviceRecord>lambdaQuery()
                        .eq(DevDeviceRecord::getDeviceCode, deviceInfo.getDeviceCode())
                        .eq(DevDeviceRecord::getDelFlag, 0)
                        .orderByDesc(DevDeviceRecord::getUpdateTime)
                        .last(" limit 1"));

                HashMap hashMap = JSON.parseObject(JSON.toJSONString(deviceRecord), HashMap.class);
                recordVoLs.add(hashMap);
            }
        }
        return recordVoLs;
    }

}
